//引入express框架
const express = require('express');
//创建网站服务器
const app = express();
require('./model/connect');
const path = require('path');
const bodyParser = require('body-parser');
const dateFormat = require('dateformat');
const template = require('art-template');
const pagination = require('mongoose-sex-page');
//向模板导入变量
template.defaults.imports.dateFormat = dateFormat;
app.locals.dateFormat = dateFormat;

app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'public')));
//引入express-session模块
const session = require('express-session');
//配置session
app.use(session({
  secret: 'secret key',
  saveUninitialized: false
}));
const home = require('./route/home');
const admin = require('./route/admin');
const {User} = require('./model/user');
const {Article} = require('./model/article');
const {Category} = require('./model/Category');
const guard = require('./middleware/loginGuard');
app.set('views',path.join(__dirname,'views'));
app.set('view engine','html');
app.engine('html',require('express-art-template'));
//打开网站首页
app.get('/',async (req,res)=>{
  let page = req.query.page;
  //文章分类
  let category = await Category.find();
  //所有文章
  let articles = await pagination(Article).find({state: 1}).page(page).size(6).display(5).populate('author').exec();
  articles = JSON.stringify(articles);
  articles = JSON.parse(articles);
  res.render('index',{
    articles,
    category
  });
});
//渲染登录页面
app.get('/toLoginPage',(req,res)=>{
  res.render('login');
});
//处理登录功能
app.post('/login',async (req,res)=>{
  let user = await User.findOne({username: req.body.username});
  if(user){
    if(user.password == req.body.password && user.role == '管理员'){
      //保存登录的用户名
      req.session.username = user.username;
      req.session.role = user.role;
      req.session.id = user._id;
      //保存登录的用户信息
      req.app.locals.userInfo = user;
      //如果是管理员，跳转后台首页
      res.redirect('/admin/index');
      //res.send('登陆成功，管理员！！！');
    }else if(user.password == req.body.password && user.role == '用户'){
      //保存登录的用户名
      req.session.username = user.username;
      req.session.role = user.role;
      req.session.id = user._id;
      //保存登录的用户信息
      req.app.locals.userInfo = user;
      //如果是用户，跳转博客首页
      res.redirect('/');
      //res.send('登陆成功，用户！！！');
    }else{
      res.render('error',{
        message: '用户名或密码错误！！！'
      });
    }
  }else{
    res.render('error',{
      message: '用户名或密码错误！！！'
    });
  }
});
//拦截请求，判断用户是否登录
app.use('/admin',guard);
//用户退出功能
app.get('/logout',(req,res)=>{
  req.session.destroy(function (){
    //删除session
    delete req.session;
    res.clearCookie('connect.sid');
    req.app.locals.userInfo =null;
    //重定向到登录页面
    res.redirect('/');

  });
});
app.use('/home',home);
app.use('/admin',admin);

//监听端口
app.listen(80);
console.log('网站服务器启动成功！');